/**
 * Created by Ysssssss on 2021/5/25.
 */

import React, {forwardRef, useState, useCallback, useContext, useEffect, useRef} from 'react'
import { Row } from "antd";
import CustomizeModal, {CustomizeModalButton, CustomizeModalContext} from "@common/presentational/CustomizeModal";
import {CustomizeDndProvider, DraggableDiv} from "@common/presentational/DndSort";
import {moveToNewIndex} from "@utils/arrayHelper";
import BilinIcon from "@common/presentational/BilinIcon";



const DndSortContent = props => {
    const { callback, type } = props
    const { hide, params } = useContext(CustomizeModalContext)
    const { sortList } = params
    const [ sortListPreview, setSortListPreview ] = useState(sortList)
    let refs = {}
    sortList.forEach(item => {
        refs[item.id] = useRef()
    })

    useEffect(() => {
        setSortListPreview(sortList)
    }, [sortList])


    const sortListAction = (dragId, hoverId) => {
        let dragIndex = 0
        let hoverIndex = 0
        sortListPreview.forEach((item, i) => {
            if(item.id === dragId) {
                dragIndex = i
            }
            if(item.id === hoverId) {
                hoverIndex = i
            }
        })
        setSortListPreview(moveToNewIndex(sortListPreview, dragIndex, hoverIndex))
    }

    const submitSortResult = () => {
        callback && callback(sortListPreview, () => {
            hide()
        })
    }

    return (
        <>
            <Row className="modal-line">
                <CustomizeDndProvider>
                    { sortListPreview.map(item => (
                        <DraggableDiv
                            key={item.id}
                            id={item.id}
                            type={type}
                            dragRef={refs[item.id]}
                            moveItemFunc={sortListAction}
                            className="flex-row-between w-100 bdb-l pd-16"
                        >
                            <span>{ item.name }</span>
                            <div className="flex-vertical-center cur-move" ref={refs[item.id]}>
                                <BilinIcon type="drag" className="mgr-8"/>
                                <span>排序</span>
                            </div>
                        </DraggableDiv>
                    )) }
                </CustomizeDndProvider>
            </Row>
            <CustomizeModalButton
                onOk={submitSortResult}
                onCancel={hide}
            />
        </>
    )
}

export const DndSortModal = forwardRef((props, ref) => {
    return (
        <CustomizeModal title={props.title || '排序'} ref={ref} width={480}>
            <DndSortContent {...props} />
        </CustomizeModal>
    )
})